﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;


namespace AMing.Api.Data
{
    public class KeyValueHelper
    {
        public List<Model.KeyValue> List()
        {
            string sql = "select [key],[value] from [KeyValue]";
            SqlHelper sqlHelper = new SqlHelper();

            return sqlHelper.Read(sql);
        }

        public List<Model.KeyValue> Get(string key)
        {
            string sql = "select [key],[value] from [KeyValue] where [key]=@Key";
            SqlHelper sqlHelper = new SqlHelper();

            return sqlHelper.Read(sql,
                new SqlParameter("@Key", key)
                );
        }

        public bool Exist(string key)
        {
            var list = Get(key);

            return list != null && list.Count > 0;
        }

        public bool Add(Model.KeyValue val)
        {
            string sql = "insert into [KeyValue]([key],[value]) values (@Key,@Value)";
            SqlHelper sqlHelper = new SqlHelper();

            var result = sqlHelper.Execute(sql,
                new SqlParameter("@Key", val.Key),
                new SqlParameter("@Value", val.Value)
                );

            return result > 0;
        }

        public bool Update(Model.KeyValue val)
        {
            string sql = "update [KeyValue] set [value]=@Value where [key]=@Key";
            SqlHelper sqlHelper = new SqlHelper();
            var result = sqlHelper.Execute(sql,
                new SqlParameter("@Key", val.Key),
                new SqlParameter("@Value", val.Value)
                );

            return result > 0;
        }
        public bool Delete(string key)
        {
            string sql = "delete from [KeyValue] where [key]=@Key";
            SqlHelper sqlHelper = new SqlHelper();
            var result = sqlHelper.Execute(sql,
                new SqlParameter("@Key", key)
                );

            return result > 0;
        }

        public int CreateTable()
        {
            string sql = "create table [KeyValue]([key] varchar(100) PRIMARY KEY,[value] text not null)";
            SqlHelper sqlHelper = new SqlHelper();
            var result = sqlHelper.Execute(sql);

            return result;
        }

        public int DeleteTable()
        {
            string sql = "drop table [KeyValue]";
            SqlHelper sqlHelper = new SqlHelper();
            var result = sqlHelper.Execute(sql);

            return result;
        }
    }
}
